/**
 * ComponentUtilities.java
 * @author: liuex
 * 2008-1-8 ����10:55:41
 *
 * note: 
 */
package org.lex.awt;

import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Stack;

import org.lex.utils.text.PadUtilities;


public class ComponentUtilities {
	public static void setEnabled(boolean b, Component... c) {
		if (null == c || 0 == c.length)
			return;
		for (Component t : c)
			t.setEnabled(b);
	}

	/***************************************************************************
	 * Component hierarchy utilities
	 **************************************************************************/
	public static void setEnabled(Component root, boolean b) {
		for (Iterator<Component> iter = ComponentVisitor.bfs(root); iter.hasNext();)
			iter.next().setEnabled(b);
	}

	public static void setComponentOrientation(Component root, ComponentOrientation orientation) {
		root.setComponentOrientation(orientation);
		if (false == root instanceof Container)
			return;
		Stack<Container> stack = new Stack<Container>();
		stack.push((Container) root);
		while (false == stack.empty()) {
			Container c = stack.pop();
			Component[] children = c.getComponents();
			for (Component child : children) {
				child.setComponentOrientation(orientation);
				if (child instanceof Container)
					stack.push((Container) child);
			}
		}
	}

	/*
	 * ����Component c������ΪClass<T>�ĸ�����
	 */
	public static <T> T getAncestor(Class<T> t, Component c) {
		if (null == c || null == t)
			return null;
		Container parent = c.getParent();
		while (parent != null && !(t.isInstance(parent)))
			parent = parent.getParent();
		return t.cast(parent);
	}

	public static void dumpComponent(Component c, PrintStream out) {
		if (null == c) {
			out.print("[null]");
			return;
		}
		// find a path link to root
		ArrayList<Component> path = new ArrayList<Component>();
		path.add(c);
		Component parent = c;
		while (true) {
			parent = parent.getParent();
			if (null != parent)
				path.add(parent);
			else
				break;
		}
		int indent = 2;
		StringBuilder buf = new StringBuilder();
		Collections.reverse(path);
		for (int i = 0; i < path.size(); i++) {
			Component t = path.get(i);
			buf.setLength(0);
			PadUtilities.pad("", buf, true, i * indent, i * indent);
			buf.append("name=");
			String name = t.getName();
			if (null == name)
				buf.append("[null]");
			else
				buf.append(name);
			buf.append(", class=");
			buf.append(path.get(i).getClass().getName());
			out.println(buf.toString());
		}
	}
}
